<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="musicName">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入要搜索的关键词"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="音乐类别" prop="musicCategoryId">
        <el-select
          v-model="queryParams.musicCategoryId"
          placeholder="请选择音乐分类"
          size="small"
        >
          <el-option value="" label="全部" />
          <el-option
            v-for="(item) in categoryList"
            :value="item.musicCategoryId"
            :label="item.musicCategoryName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="showStauts">
        <el-select
          v-model="queryParams.showStauts"
          placeholder="请选择是否展示"
          size="small"
        >
          <el-option value="" label="全部" />
          <el-option value="0" label="展示" />
          <el-option value="1" label="隐藏" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="音乐名称" prop="musicName">
        <el-input
          v-model="queryParams.musicName"
          placeholder="请输入音乐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="音乐地址" prop="musicUrl">
        <el-input
          v-model="queryParams.musicUrl"
          placeholder="请输入音乐地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用次数" prop="useNum">
        <el-input
          v-model="queryParams.useNum"
          placeholder="请输入使用次数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="展示：0：展示，1：隐藏" prop="show">
        <el-input
          v-model="queryParams.show"
          placeholder="请输入展示：0：展示，1：隐藏"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除：0-否，1-是" prop="deleteFlag">
        <el-input
          v-model="queryParams.deleteFlag"
          placeholder="请输入删除：0-否，1-是"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入更新人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.updatedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['recitation:music:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['recitation:music:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['recitation:music:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recitation:music:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="musicList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="音乐id"  prop="musicId" />
      <el-table-column label="音乐名称"  prop="musicName" />
      <el-table-column label="类别"  prop="musicCategoryId">
        <template slot-scope="scope">{{ scope.row.musicCategoryId | categoryStr}}</template>
      </el-table-column>
      <el-table-column label="使用次数"  prop="useNum" />
      <el-table-column label="是否展示"  prop="showStauts">
        <template slot-scope="scope">{{ scope.row.showStauts | showStautsStr}}</template>
      </el-table-column>
      <el-table-column label="信息更新时间"  prop="updatedTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否展示" align="center" prop="showStauts" >
        <template slot-scope="scope">{{ scope.row.showStauts | showStautsStr}}</template>
      </el-table-column>
      <el-table-column label="展示：0：展示，1：隐藏" align="center" prop="show" />
      <el-table-column label="音乐地址" align="center" prop="musicUrl" />
      <el-table-column label="删除：0-否，1-是" align="center" prop="deleteFlag" />
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-headset"
            @click="handleListen(scope.row)"
            v-hasPermi="['recitation:music:listen']"
          >试听</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['recitation:music:view']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['recitation:music:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['recitation:music:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改背景音乐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="formClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="音乐ID" prop="musicId" v-if="isEdit">
          {{form.musicId}}
        </el-form-item>
        <el-form-item label="音乐名称" prop="musicName">
          <el-input v-model="form.musicName" placeholder="请输入音乐名称" />
        </el-form-item>
        <el-form-item label="音乐分类" prop="musicCategoryId" v-if="!isEdit">
          <el-select
            v-model="form.musicCategoryId"
            placeholder="请选择音乐分类"
          >
            <el-option value="" label="全部"></el-option>
            <el-option
              v-for="(item) in categoryList"
              :value="item.musicCategoryId"
              :label="item.musicCategoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传音乐" prop="musicUrl" v-if="!isEdit">
          <!-- <el-input v-model="form.musicUrl" placeholder="因客户给的上传链接无法访问，暂时手填" /> -->
          <file-upload :limit="1" v-model="form.musicUrl" :fileType="fileType"></file-upload>
        </el-form-item>
        <el-form-item label="是否展示" prop="showStauts" v-if="isEdit">
          <el-select
            v-model="form.showStauts"
            placeholder="请选择是否展示"
          >
            <el-option :value="0" label="展示" />
            <el-option :value="1" label="隐藏" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用次数" prop="useNum" v-if="isEdit">
          {{current_row.useNum}}
        </el-form-item>
        <el-form-item label="音频播放" prop="musicUrl" v-if="isEdit">
          <audio-player :url="form.musicUrl" ref="audioFormPlayer"></audio-player>
          <!-- <audio :src="form.musicUrl" style="display: block; width: 100%; height: 50px;" controls controlsList="nodownload"></audio> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 试听窗口 -->
    <el-dialog :title="listenTitle" :visible.sync="openListen" width="500px" append-to-body @close="onListenClose">
      <el-row>
        <el-col :span="24">
          <audio-player :url="listenUrl" ref="audioPlayer"></audio-player>
          <!-- <audio :src="listenUrl" style="display: block; width: 100%; height: 50px;" controls controlsList="nodownload"></audio> -->
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listMusic, getMusic, delMusic, addMusic, updateMusic } from "@/api/recitation/music";
import { listCategory} from "@/api/recitation/category";
import AudioPlayer from "@/components/AudioPlayer";

export default {
  name: "Music",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 背景音乐表格数据
      musicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出窗里是否是修改模式
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        musicCategoryId: null,
        musicName: null,
        musicUrl: null,
        useNum: null,
        show: null,
        deleteFlag: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      },
      // 音乐分类列表
      categoryList: [],
      // 上传的文件列表
      fileType: [ "mp3", "aac", "wma"],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        musicName: [ { required: true, message: "请输入音乐名称"}],
        musicCategoryId: [ { required: true, message: "请选择音乐分类"}],
        musicUrl: [ { required: true, message: "请上传音乐文件"}],
        showStauts: [ { required: true, message: "请选择是否展示"}],
      },

      // 打开试听窗
      openListen: false,
      // 试听的链接
      listenUrl: "",
      listenTitle: "",

      // 当前操作的 row
      current_row: {},
    };
  },
  components:{
    AudioPlayer
  },
  filters: {
    categoryStr( val){
      let list = window.vueIns ? window.vueIns.categoryList : [];
      let value = "[未知]";
      list.forEach( (item, index) =>{
        if( item.musicCategoryId == val){
          value = item.musicCategoryName;
        }
      })
      return value;
    },
    showStautsStr(val){
      return val == 0 ? "展示" : "隐藏";
    }
  },
  created() {
    window.vueIns = this;
    listCategory().then( (res) => {
      console.log( "+++++++++++listCategory", res);
      if( res.code == 200){
        this.categoryList = res.rows;
      }
    });
    this.getList();
  },
  methods: {
    /** 查询背景音乐列表 */
    getList() {
      this.loading = true;
      listMusic(this.queryParams).then(response => {
        this.musicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        musicId: null,
        musicCategoryId: null,
        musicName: null,
        musicUrl: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.musicId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.open = true;
      this.title = "添加背景音乐";
    },
    /** 试听按钮操作 */
    handleListen( row){
      this.listenUrl = row.musicUrl;
      this.listenTitle = row.musicName + " 试听";
      this.openListen = true;
    },
    onListenClose(){
      this.$refs.audioPlayer.stop();
    },
    formClose(){
      this.$refs.audioFormPlayer.stop();
    },
    /** 查看按钮操作 */
    handleView( row){
      this.current_row = row;
      this.reset();
      const musicId = row.musicId;
      this.form = {
        musicId : musicId + "",
        musicName : row.musicName,
        musicUrl : row.musicUrl,
        showStauts : row.showStauts,
      };
      this.isEdit = true;
      this.open = true;
      this.title = "查看背景音乐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const musicId = row.musicId;
      this.form = {
        musicId : musicId + "",
        musicName : row.musicName,
        musicUrl : row.musicUrl,
        showStauts : row.showStauts,
      };
      this.isEdit = true;
      this.open = true;
      this.title = "修改背景音乐";
      // getMusic(musicId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改背景音乐";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.musicId != null) {
            updateMusic(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMusic(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let name = row.musicName;
      const musicIds = row.musicId ;
      this.$confirm('是否确认删除名为"' + name + '"的背景音乐?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          this.loading = true;
          return delMusic(musicIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('recitation/music/export', {
        ...this.queryParams
      }, `recitation_music.xlsx`)
    }
  }
};
</script>
